package com.achunt.justtype

import android.content.Context
import android.content.ContentResolver
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Filter
import android.widget.Filterable
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import android.util.Log
import android.provider.ContactsContract
import android.graphics.BitmapFactory
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.content.res.AssetFileDescriptor
import java.util.*
import java.io.InputStream
import java.io.FileNotFoundException
import java.io.IOException

class ContactsAdapter(
    jt: EditText,
    cr: ContentResolver,
    cName: ArrayList<String>,
    cNumber: ArrayList<String>,
    cUri: ArrayList<Uri>,
) :
    RecyclerView.Adapter<ContactsAdapter.ViewHolder>(), Filterable {
    public var cListUri: MutableList<Uri> = ArrayList()
    public var cListNumber: MutableList<String>
    private var ljt: EditText

    init {
        ljt = jt
        lcr = cr
        cListName = cName
        cListNameNew = ArrayList()
        cListUriNew = ArrayList()
        cListNumber = cNumber
        cList = ArrayList()
        cListAll = ArrayList()
        for (i in cName.indices) {
            cListUri.add(cUri[i])
            cListName.add(cName[i])
            cListNumber.add(cNumber[i])
            cList.add(cName[i])
        }
        cList.sort()
        cListAll.addAll(cList)
    }

    override fun getItemCount(): Int {
        return cList!!.size
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(charSequence: CharSequence): FilterResults {
                val charString = charSequence.toString()
                if (charString.isEmpty()) {
                    cListNameNew = cList
                    cListUriNew = cListUri
                } else {
                    val filteredList: MutableList<String> = ArrayList()
                    val filteredUriList: MutableList<Uri> = ArrayList()
                    var i = 0
                    for (c in cListAll) {
                        if (c.lowercase(Locale.getDefault())
                                .startsWith(charString.lowercase(Locale.getDefault()))
                        ) {
                            filteredList.add(c)
                            filteredUriList.add(cListUri[i])
                        }
                     i++
                    }
                    cListNameNew = filteredList
                    cListUriNew = filteredUriList
                }
                val filterResults = FilterResults()
                filterResults.values = cListNameNew
                return filterResults
            }

            override fun publishResults(charSequence: CharSequence, filterResults: FilterResults) {
                cList.clear()
                notifyDataSetChanged()
                cList.addAll((filterResults.values as ArrayList<String>))
                notifyDataSetChanged()
            }
        }
    }

    private fun loadContactPhotoThumbnail(photoData: String?): Bitmap? {
        var afd: AssetFileDescriptor? = null
        try {
            val thumbUri: Uri = Uri.parse(photoData)
            afd = lcr?.openAssetFileDescriptor(thumbUri, "r")
            return afd?.fileDescriptor?.let {fileDescriptor ->
                BitmapFactory.decodeFileDescriptor(fileDescriptor, null, null)
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        } finally {
            try {

                afd?.close()
                return null
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) {
          if(cList.size == 0)
            return
            try {
                val cLabel = cList[i]
                val textView = viewHolder.textView
                textView.text = cLabel
                val imageView: ImageView = viewHolder.img
                val maxUri = cListUriNew.size
                    try {
                      val stream: InputStream? = if (maxUri > i)
                        ContactsContract.Contacts.openContactPhotoInputStream(lcr, cListUriNew[i])
                        else
                        null
                      val draw: Drawable? = Drawable.createFromStream(stream, null)
                      if(draw != null) {
                        imageView.setImageDrawable(draw)
                      } else {
                        imageView.setImageResource(R.drawable.no_contact_image);
                      }
                      imageView.visibility = View.VISIBLE
                    } catch (e: Exception) {
                      e.printStackTrace()
                    }
            } catch (e: Exception) {
                e.printStackTrace()
                val cLabel = "No contact found"
                val textView = viewHolder.textView
                textView.text = cLabel
                val imageView = viewHolder.img
                imageView.visibility = View.INVISIBLE
            }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val view: View = inflater.inflate(R.layout.jt_item_row_layout, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var textView: TextView
        var img: ImageView
        var textField: String

        init {
            textView = itemView.findViewById(R.id.jt_app_name)
            img = itemView.findViewById(R.id.jt_app_icon)
            textField = JustType.textSend
            itemView.setOnClickListener { v: View ->
              val pos = this.getLayoutPosition()
              val uri = cListUriNew[pos]
              val context = v.context
              val intent = Intent(Intent.ACTION_VIEW)
              ljt.setText("")
              intent.setData(uri);
              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
              context.startActivity(intent)
            }
        }
    }

    public fun selectFirst(v: View): Boolean {
      try {
        val uri = cListUriNew[0]
        val context = v.context
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setData(uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        context.startActivity(intent)
        return true
      } catch (e: Exception) {
        return false
      }
    }

    public companion object {
        lateinit var cListName: MutableList<String>
        lateinit var cListNameNew: List<String>
        lateinit var cListUriNew: List<Uri>
        lateinit var cList: MutableList<String>
        lateinit var cListAll: MutableList<String>
        lateinit var lcr: ContentResolver
    }
}
